<template>
  <el-dialog
    :title="$t('msg.excel.roleDialogTitle')"
    :model-value="modelValue"
    @close="closed"
  >
    <el-checkbox-group v-model="userRoleTitleList">
      <el-checkbox
        v-for="item in allRoleList"
        :key="item.id"
        :label="item.title"
      ></el-checkbox>
    </el-checkbox-group>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closed">{{ $t('msg.universal.cancel') }}</el-button>
        <el-button type="primary" @click="onConfirm">{{
          $t('msg.universal.confirm')
        }}</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { roleList } from '@/api/role'
import { watchSwitchLang } from '@/utils/i18n'
import { defineProps, defineEmits, watch, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useI18n } from 'vue-i18n'

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  currentRoleTitle: {
    type: Array
  }
})

const emits = defineEmits(['update:modelValue', 'updateRole'])

const closed = () => {
  emits('update:modelValue', false)
}

const i18n = useI18n()
// 确认更新用户角色
const onConfirm = () => {
  const roles = userRoleTitleList.value.map((title) => {
    return allRoleList.value.find((role) => role.title === title)
  })
  ElMessage.success(i18n.t('msg.role.updateRoleSuccess'))
  console.log('新角色', roles)
  emits('updateRole')
  closed()
}

// 获取所有角色
const allRoleList = ref([])
const getListData = async () => {
  allRoleList.value = await roleList()
}
getListData()
watchSwitchLang(getListData)

// 当前角色
const userRoleTitleList = ref([])
watch(
  () => props.currentRoleTitle,
  (val) => {
    if (val) {
      userRoleTitleList.value = props.currentRoleTitle.map((item) => item.title)
    }
  }
)

// 监听dialog 保证每次打开都是最新数据
</script>

<style lang="scss" scoped>
</style>
